package org.schhx;

import org.junit.Assert;
import org.schhx.io.Resources;
import org.schhx.mapper.UserMapper;
import org.schhx.pojo.User;
import org.schhx.session.SqlSession;
import org.schhx.session.SqlSessionFactory;
import org.schhx.session.SqlSessionFactoryBuilder;

import java.io.InputStream;

/**
 * @author shanchao
 * @date 2021/1/30
 */
public class CrudTest {

    public static void main(String[] args) throws Exception {
        InputStream inputStream = Resources.getResourceAsStream("sqlSessionMap.xml");
        SqlSessionFactory sqlSessionFactory = SqlSessionFactoryBuilder.build(inputStream);
        SqlSession session = sqlSessionFactory.open();

        UserMapper userMapper = session.getMapper(UserMapper.class);

        // 新增一个用户
        User user = new User();
        user.setId(3);
        user.setUsername("张三");
        user.setPassword("123");
        user.setBirthday("2019-12-12");
        int insertResult = userMapper.save(user);
        System.out.println("insertResult:\n" + insertResult);
        Assert.assertEquals(1, insertResult);

        // 通过id查询刚新增的用户
        User selectResult = userMapper.findById(3);
        System.out.println("selectResult:\n" + selectResult);
        Assert.assertNotNull(selectResult);

        // 修改用户名
        user.setUsername("李四");
        userMapper.updateById(user);
        User updateResult = userMapper.findById(3);
        System.out.println("updateResult:\n" + updateResult);
        Assert.assertNotNull(updateResult);
        Assert.assertEquals("李四", updateResult.getUsername());

        // 通过id删除刚新增的用户
        int deleteResult = userMapper.deleteById(3);
        System.out.println("deleteResult:\n" + deleteResult);
        Assert.assertEquals(1, deleteResult);

        Assert.assertNull(userMapper.findById(3));
    }
}
